<template>
	<view class="chatInterface">
		<view class="scroll-view">
			<view class="all-history-loaded">
				{{allHistoryLoaded ? '已经没有更多的历史消息' : '下拉获取历史消息'}}
			</view>
			<view v-for="(message,index) in messages" :key="index">
				<view class="message-item" :class="{'self' : message.sendUserId ==currentUser.userId}">
					<view class="avatar" v-if="message.sendUserId != currentUser.userId">
						<image :src="friend.acceptUserIcon"></image>
					</view>
					<view class="avatar" v-else>
						<image :src="currentUser.icon"></image>
					</view>
					<view class="content">
						<view v-if="message.type == 'text'" v-html="renderTextMessage(message)"></view>
					</view>
				</view>
			</view>
		</view>
		<view class="action-box">
			<view class="action-top">
				<view class="message-input">
					<input type="text" maxlength="700" placeholder="发送消息" v-model="content">
				</view>
				<span class="send-message-btn" :class="content?'end-message-btn_content':''"
					@click="sendTextMessage">发送</span>
			</view>
		</view>
	</view>
</template>

<script>
	var isOnMessage = false;
	var _self;
	export default {
		name: "privateChat",
		data() {
			return {
				//聊天文本框
				content: '',
				friend: null,
				currentUser: null, //自己
				//已经接收到的消息
				messages: [],
				//已经加载完所有历史消息
				allHistoryLoaded: false,
				page: 1
			}
		},
		onReady() {
			uni.setNavigationBarTitle({
				title: "与" + this.friend.acceptUserName + "聊天"
			});
		},
		onShow() {},
		onLoad(options) {
			_self = this;
			_self.friend = JSON.parse(options.user);
			_self.currentUser = _self.$store.state.user;
			_self.getHistory();
			if (!isOnMessage) {
				isOnMessage = true;
				_self.$socket.state.socketTask.onMessage(function(res) {
					console.log('收到服务器内容：' + res.data)
					var message = JSON.parse(res.data);
					message.acceptUserId = _self.currentUser.userId;
					message.acceptUserName = _self.currentUser.name;
					message.acceptUserIcon = _self.currentUser.icon;
					message.sendUserId = _self.friend.acceptUserId;
					message.sendUserName = _self.friend.acceptUserName;
					message.sendUserName = _self.friend.acceptUserIcon;
					_self.messages.push(message)
					_self.scrollToBottom();
				});
			}
		},
		onPullDownRefresh(e) {
			console.log("开始下拉刷新")
			if (!_self.allHistoryLoaded) {
				_self.getHistory();
			} else {
				uni.stopPullDownRefresh();
			}
		},
		onUnload() {

		},
		methods: {
			renderTextMessage(message) {
				return '<span class="text-content">' + message.text + '</span>'
			},
			scrollToBottom() {
				this.$nextTick(function() {
					uni.pageScrollTo({
						scrollTop: 2000000,
						duration: 10
					})
				});
			},
			sendTextMessage() {
				var content = this.content;
				var data = {
					relationId: this.friend.id,
					type: 'text',
					text: content,
					sendUserId: this.currentUser.userId,
					sendUserName: this.currentUser.name,
					sendUserIcon: this.currentUser.icon,
					acceptUserId: this.friend.acceptUserId,
					acceptUserName: this.friend.acceptUserName,
					acceptUserIcon: this.friend.acceptUserIcon,
					userInfo: this.currentUser,
					acceptUserInfo: this.friend
				}
				this.messages.push(data)
				this.content = null;
				_self.$socket.dispatch("WEBSOCKET_SEND", JSON.stringify(data));
				this.scrollToBottom();
				//防止输入法关闭后消息无法滚动到底部  再首次滚动后延时1秒再次滚动一次
				setTimeout(function() {
					_self.scrollToBottom();
				}, 1000)
			},
			getHistory() {
				_self.xhttp.request({
					url: "/chat/record/list", //仅为示例，并非真实接口地址。
					method: "POST",
					data: {
						sendUserId: _self.currentUser.userId,
						acceptUserId: _self.friend.acceptUserId,
						page: _self.page,
						pageSize: 10
					},
					header: {
						'Content-Type': 'application/json'
					}
				}).then(res => {
					if (res.data.code == 0) {
						if (res.data.data.data.length < 10) {
							_self.allHistoryLoaded = true
						} else {
							_self.allHistoryLoaded = false
						}
						var data = res.data.data.data;
						var msgs = _self.messages;
						if (_self.page == 1) {
							for (var i = data.length - 1; i >= 0; i--) {
								msgs.push(data[i])
							}
							_self.messages = msgs;
						} else {
							for (let index in msgs) {
								data.push(msgs[index])
							}
							_self.messages = data;
						}
						uni.stopPullDownRefresh();
						if (_self.page == 1) {
							this.scrollToBottom();
						}
					} else {
						plus.nativeUI.toast(res.data.msg);
						uni.stopPullDownRefresh();
					}
					_self.page = _self.page + 1;
				}).catch(err => {
					uni.stopPullDownRefresh();
				})
			}
		}
	}
</script>

<style>
	@import url("../../../static/css/chatInterface.css");

	.end-message-btn_content {
		color: red !important;
	}
</style>
